﻿using System;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Text.RegularExpressions;
using System.Xml.Linq;
using Jungle.Code.DAL;
using Jungle.Code.BLL;
using Jungle.Code.Core;
using Jungle.Code.Utils;


using Jungle.Prodamo.AdvertManager;
using Jungle.Prodamo.MostNeedFunctions;
using Jungle.Prodamo.Core;
using Jungle.Prodamo.PaySystem;

public partial class User : BaseUserModule
{
    SessionKeeper thisSession = new SessionKeeper();
    protected override void OnInit(EventArgs e)
    {
        btn_SendMessage.PostBackUrl = Request.RawUrl;
        btn_Update.PostBackUrl = Request.RawUrl;
        thisSession.SessionId = Session.SessionID.ToString();
        thisSession.GetData();

        if (Request["cmd"] != null)
        {
            switch (Request["cmd"].ToString())
            {
                case "Add":
                    if (thisSession.UserId != -1)
                    {
                        tr_Email.Visible = false;
                        tr_Password.Visible = false;
                        tr_FastKey.Visible = false;
                    }
                    AdvertMenu.Visible = true;
                    AdvertMenu.ActiveViewIndex = 0;
                    LoadData();
                    break;
                case "Show":
                    AdvertMenu.Visible = true;
                    AdvertMenu.ActiveViewIndex = 1;
                    LoadAdvert();
                    break;
                case "Rubr":
                    byrubr1.RubrikId = Convert.ToInt32(Request["Id"]);
                    byrubr1.Visible = true;
                    break;
                case "My":
                    ByUser1.UserId = thisSession.UserId;
                    ByUser1.Visible = true;
                    break;
                case "Edit":
                    AdvertMenu.Visible = true;
                    AdvertMenu.ActiveViewIndex = 2;
                    LoadData();
                    LoadAdvertForEdit();
                    break;
            }
        }
        else rblist1.Visible = true;

        base.OnInit(e);
    }

    protected void LoadData()
    {
        Rubrik rbs = new Rubrik();
        rbs.GetAll();
        foreach (Rubrik rb in rbs.RubrikList)
        {
            if(rb.ParentId == 0)
            ddl_Rubrik.Items.Add(new ListItem(rb.Title, rb.RubrikId.ToString()));

            Rubrik childs = new Rubrik();
            childs.ParentId = rb.RubrikId;
            childs.GetByParentId();

            if(childs.RubrikList.Count > 0)
            foreach (Rubrik child in childs.RubrikList)
            {
                ddl_Rubrik.Items.Add(new ListItem(" --- " + child.Title, child.RubrikId.ToString()));
            }
        }

        UserManager um = new UserManager();
        um.UserId = thisSession.UserId;
        um.GetById();
        tb_Phone.Text = um.Phone;

        btn_AddAdvert.PostBackUrl = Request.RawUrl;
    }
    protected void LoadAdvert()
    {
        if (Request["Id"] != null)
        {
            if (thisSession.UserId != -1)
            {
                tbl_Message.Visible = true;
            }

            Advert adv = new Advert();
            adv.AdvertId = Convert.ToInt32(Request["Id"]);
            adv.GetById();

            lb_Title.Text = adv.Title;
            switch (adv.Type)
            {
                case 0: lb_Type.Text = "Продажа"; break;
                case 1: lb_Type.Text = "Покупка"; break;
                case 2: lb_Type.Text = "Обмен"; break;
            }
            lb_Price.Text = adv.Price.ToString();
            switch (adv.Currency)
            {
                case 0: lb_Price.Text += " грн."; break;
                case 1: lb_Price.Text += " евро"; break;
                case 2: lb_Price.Text += " $"; break;                
            }

            UserManager um = new UserManager();
            um.UserId = adv.UserId;
            um.GetById();

            if (um.UsertType) lb_UserInfo.Text = um.UserLink();
            else lb_UserInfo.Text = um.CompanyLink();
            lb_PubDate.Text = adv.PubDate.ToString();
            lb_LeftTime.Text = Functions.GetTimeLeft(adv.EndDate);

            ABR abr = new ABR();
            abr.AdvertId = adv.AdvertId;
            abr.GetByAdvert();
            foreach (Rubrik rb in abr.RubrikList)
            {
                lb_Rubrik.Text += rb.Title + " ";
            }

            lb_Contacts.Text = "<a href=\"mailto:" + um.Email + "\">" + um.Email + "</a><br/>";
            if (um.Phone.Length > 0) lb_Contacts.Text += "тел: " + um.Phone + "<br/>";
            if (um.Faks.Length > 0) lb_Contacts.Text += "факс: " + um.Faks;

            lb_Body.Text = adv.Body;
            if (adv.ImageUrl.IndexOf("~/") != -1) img_Image.ImageUrl = adv.ImageUrl;
            else img_Image.Visible = false;

        }
    }
    protected void LoadAdvertForEdit()
    {
        if (Request["Id"] != null)
        {
            int id = Convert.ToInt32(Request["Id"]);
            Advert adv = new Advert();
            adv.AdvertId = id;
            adv.GetById();

            tb_Zagolovok.Text = adv.Title;
            ddl_Tip.SelectedValue = adv.Type.ToString();
            tb_Cena.Text = adv.Price.ToString();
            ddl_Valuta.SelectedValue = adv.Currency.ToString();
            tb_Body2.Text = adv.Body;

            if (adv.ImageUrl == "NONE")
            {
                img_TovarImg.Visible = false;
            }
            else
            {
                img_TovarImg.ImageUrl = adv.ImageUrl;
            }
        }
    }
    protected void UpdateAdvert(object sender, EventArgs e)
    {
        if (Request["Id"] != null)
        {
            int id = Convert.ToInt32(Request["Id"]);
            Advert adv = new Advert();
            adv.AdvertId = id;
            adv.GetById();

            adv.UserId = thisSession.UserId;
            adv.Title = tb_Zagolovok.Text.Trim();
            adv.Type = Convert.ToInt32(ddl_Tip.SelectedValue);
            adv.EndDate = DateTime.Now.AddDays(Convert.ToInt32(ddl_Srok.SelectedValue));
            adv.Price = Convert.ToDouble(tb_Cena.Text.Trim());
            adv.Currency = Convert.ToInt32(ddl_Valuta.SelectedValue);
            adv.Body = tb_Body2.Text.Trim();

            if (fu_TovarImg.HasFile)
            {
                fu_TovarImg.PostedFile.SaveAs(Server.MapPath("~/Images/AdvertsImg/" + fu_TovarImg.FileName));
                adv.ImageUrl = "~/Images/AdvertsImg/" + fu_TovarImg.FileName;
            }

            adv.Update();
            Response.Redirect(UrlHelper.GetSiteUrl() + "/ru/adverts.aspx?cmd=My");
        }        
    }
    protected void AddAdvert(object sender, EventArgs e)
    {
        ValidBlock.InnerHtml = "";
        bool valid = true;
        if (tb_Title.Text.Trim().Length < 1) { valid = false; ValidBlock.InnerHtml += "Укажите заголовок <br/>"; }
        if (tb_Price.Text.Trim().Length < 1) { valid = false; ValidBlock.InnerHtml += "Укажите цену <br/>"; }
        if (tb_Body.Text.Trim().Length < 1) { valid = false; ValidBlock.InnerHtml += "Опишите хоть немного ваше объявление<br/>"; }

        ccJoin.ValidateCaptcha(tb_Cap.Text);
        if (thisSession.UserId != -1)
        {
            NewAdvert(valid);
        }
        else
        {
            if (tb_FastKey.Text.Trim().Length == 6)
            {
                FastEnter();
            }
            else
            {

                UserManager um = new UserManager();
                um.NickName = tb_Email.Text;
                um.Password = Functions.getMd5Hash(tb_Password.Text.Trim());

                if (um.Login())
                {
                    thisSession.SessionId = Session.SessionID.ToString();
                    thisSession.UserId = um.UserId;
                    thisSession.UserLogin = um.NickName;
                    thisSession.AdminLogin = "none";

                    thisSession.Create();

                    NewAdvert(valid);
                }
                else
                {
                    if (!um.CheckNickName())
                    {
                        ValidBlock.InnerHtml = "Пользователь с таким Email уже зарегистрирован. Если это вы, то вы просто ввели неверный пароль.";
                    }
                    else
                    {
                        FastRegister();
                        if (um.Login())
                        {
                            thisSession.SessionId = Session.SessionID.ToString();
                            thisSession.UserId = um.UserId;
                            thisSession.UserLogin = um.NickName;
                            thisSession.AdminLogin = "none";

                            thisSession.Create();

                            NewAdvert(valid);
                        }
                    }
                }
            }
        }
    }
    protected void SendMessage(object sender, EventArgs e)
    {
        Advert a = new Advert();
        a.AdvertId = Convert.ToInt32(Request["Id"]);
        a.GetById();

        UserManager u = new UserManager();
        UserManager um = new UserManager();
        um.UserId =  thisSession.UserId;
        um.GetById();
        u.UserId = a.UserId;
        u.GetById();

        u.SendEmail(u.Email, "prodamo.com: сообщение по объявлнию " + a.Title, tb_Message.Text.Trim() + "    Cообщение получено от " + um.UserLink());
        tbl_Message.Visible = false;
        div_result.InnerHtml = "Сообщение отправлено";
    }
    protected void NewAdvert(bool valid)
    {
        if (valid && ccJoin.UserValidated)
        {
            Advert adv = new Advert();
            adv.UserId = thisSession.UserId;
            adv.Title = tb_Title.Text.Trim();
            adv.Type = Convert.ToInt32(ddl_Type.SelectedValue);
            adv.Body = tb_Body.Text.Trim();
            adv.EndDate = DateTime.Now.AddDays(Convert.ToInt32(ddl_Time.SelectedValue));
            adv.Price = Convert.ToDouble(tb_Price.Text.Trim());
            adv.Currency = Convert.ToInt32(ddl_Currency.SelectedValue);
            if (!fu_Image.HasFile) adv.ImageUrl = "NONE";
            else
            {
                fu_Image.PostedFile.SaveAs(Server.MapPath("~/Images/AdvertsImg/" + fu_Image.FileName));
                adv.ImageUrl = "~/Images/AdvertsImg/" + fu_Image.FileName;
            }
            adv.Add();

            ABR abr = new ABR();
            abr.RubrikId = Convert.ToInt32(ddl_Rubrik.SelectedValue);
            abr.AdvertId = adv.AdvertId;
            abr.Add();

            UserManager um = new UserManager();
            um.UserId = thisSession.UserId;
            um.GetById();
            if (tb_Phone.Text.Trim().Length > 1)
            {
                um.Phone = tb_Phone.Text.Trim();
                um.Update();
            }

            Response.Redirect("~/ru/adverts.aspx?cmd=Show&Id=" + adv.AdvertId.ToString());
        }
        else
            ValidBlock.InnerHtml += "Вы ввели неверный код подтверждения";    
    }
    protected void FastRegister()
    {
        if (tb_Email.Text.IndexOf("@") != -1)
        {
            UserManager um = new UserManager();
            um.NickName = tb_Email.Text.Trim();

            string password = tb_Password.Text.Trim();
            um.Fname = "Безымянный";
            um.Oname = "Безымянный";
            um.Iname = "Безымянный";
            um.Email = um.NickName;
            um.Sex = true;
            um.Organization = um.NickName;
            um.Edrpou = "NONE";
            um.WorkTime = "NONE";
            um.Web = "NONE";
            um.Logo = "~/Images/1px.gif";
            um.Map = "~/Images/1px.gif";
            um.Deliver = "";
            um.Credit = "";
            um.Country = "1";
            um.Zip = "00000";
            um.City = "1";
            um.Address = "нет";
            um.Phone = tb_Phone.Text;
            um.Faks = "";
            um.BirthDay = DateTime.Now;
            um.Password = Functions.getMd5Hash(password);
            um.UsertType = true;
            um.FastKey = GetRandom("");
            um.Add();

            Account acc = new Account();
            acc.CreateAccount(um.UserId);

            string body = "Вы были зарегистрированы на prodamo.com. Данные для доступа: Email:" + um.NickName + ". Password: " + password + ". Ключ быстрого доступа: " + um.FastKey;
            um.SendEmail(um.Email, "prodamo.com: подтверждение регистрации", body);

        }
        else ValidBlock.InnerHtml = "Вы ввели некорректный Email";
    }
    protected void FastEnter()
    {
        UserManager um = new UserManager();
        um.FastKey = tb_FastKey.Text;
        um.GetByFastKey();

        if (um.UserId != 0)
        {
            if (um.Login())
            {
                thisSession.UserId = um.UserId;
                thisSession.SessionId = Session.SessionID.ToString();
                thisSession.UserLogin = um.NickName;
                thisSession.AdminLogin = "none";
                thisSession.Create();

                NewAdvert(true);
            }
        }
        else
        {
            ValidBlock.InnerHtml = "Вы ввели некорректный код";
        }
    }
    protected string GetRandom(string str)
    {
        string mask = "1234567890qwertyuiopasdfghjklzxcvbnm";
        System.Random rnd = new Random();
        for (int i = 0; i < 6; i++)
        {
            str += mask[rnd.Next(0, 35)];
        }
        return str;
    }
}
